<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-08-01 15:29
 *
 * Version: 2.0
 */

namespace App\Modules\Employee\Criterias;


use Flower\Core\Repository\Contracts\CriteriaInterface;
use Flower\Core\Repository\Contracts\RepositoryInterface;
use Illuminate\Support\Facades\DB;

class GetStoreBarberListCriteria implements CriteriaInterface
{
    protected $storeId;

    public function __construct($storeId)
    {
        $this->storeId = $storeId;
    }

    public function apply($model, RepositoryInterface $repository)
    {

        $store_id = $this->storeId;

        $store_query = DB::table('store')
            ->selectRaw('id,user_id')
            ->where('id',$store_id)
            ->groupBy('user_id');

        $select = [
            'hx_user.id',
            'hx_user.salary',
            'GROUP_CONCAT(hx_user_store.rid) as role',
            'hx_user.nick',
            'hx_picture.image as portrait',
            'IF(hx_store.id IS NULL,0,1) as is_boss'
        ];
        $select = implode($select,',');

        return $model->selectRaw($select)
            ->leftJoin('user_store','user.id','user_store.uid')
            ->leftJoin('picture','user.portrait','picture.id')
            ->leftJoin(\DB::raw("({$store_query->toSql()}) as hx_store"),function ($join) use($store_query){
                $join->mergeBindings($store_query)->on('user.id','=','store.user_id');
            })
            ->groupBy('user.id')
            ->where('user_store.sid',$store_id)
            ->orderBy('is_boss','desc');
    }
}